package token

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	"wrblog-api-go/app/common/constants"
	"wrblog-api-go/config"
	"wrblog-api-go/pkg/redis"
	"wrblog-api-go/pkg/utils"
)

type ClientInfo struct {
	IpAddr        string `json:"ipAddr" form:"ipAddr"`
	LoginLocation string `json:"loginLocation" form:"loginLocation"`
	Browser       string `json:"browser" form:"browser"`
	Os            string `json:"os" form:"os"`
}

// GetToken 获取请求体中的token
func GetToken(c *gin.Context) string {
	tokenInfo := c.GetHeader(config.Conf.ConfigInfo.Token.Header)
	if tokenInfo != "" {
		if strings.Contains(tokenInfo, constants.TOKEN_PREFIX) {
			return tokenInfo[len(constants.TOKEN_PREFIX):]
		} else {
			return tokenInfo
		}
	}
	//支持cookie鉴权
	token, _ := c.Cookie("WrBlog-Token")
	return token
}

func CheckLogin(c *gin.Context) (loginUser LoginUser, ok bool) {
	token := GetToken(c)
	claims, ok := GetTokenVal(token)
	if !ok {
		return
	}
	info := redis.Get(fmt.Sprintf("%s%v:%v", constants.LOGIN_USER_KEY, claims.UserId, claims.Uid))
	if utils.IsEmpty(info) {
		return loginUser, false
	}
	json.Unmarshal([]byte(info), &loginUser)
	RefreshToken(claims.Uid, loginUser)
	return
}

func GetLoginUser(c *gin.Context) (loginUser LoginUser) {
	val, exists := c.Get("loginUser")
	if exists {
		return val.(LoginUser)
	}
	return
}

func GetUserId(c *gin.Context) int64 {
	loginUser := GetLoginUser(c)
	if utils.IsEmpty(loginUser) {
		return 0
	}
	return loginUser.UserId
}

func IsAdmin(userId int64) bool {
	return userId == 10000000000
}

func GetUk(c *gin.Context) string {
	loginUser := GetLoginUser(c)
	if utils.IsEmpty(loginUser) {
		return ""
	}
	return loginUser.Uk
}
